package com.cf.game.im.handler.histroy;

import com.cf.constant.EnumReturnCode;
import com.cf.game.im.dao.ChatMapper;
import com.cf.game.im.handler.Handler;
import com.cf.game.im.model.ChatMsg;
import com.cf.game.msg.ChatHistoryRequest;
import com.cf.game.msg.ChatHistroyResponse;
import com.cf.game.msg.ChatType;
import com.cf.game.msg.Response;
import com.cf.game.node.NodeService;
import com.cf.mapper.BeanMapper;
import com.cf.util.ObjectJsonUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.vertx.core.eventbus.EventBus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * boot-game-SingleChatHistroyHandler
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/8/1 上午 11:50
 */
@Slf4j
@Component
public class SingleChatHistroyHandler implements Handler {

    @Autowired
    private BeanMapper beanMapper;

    @Autowired
    private ChatMapper chatMapper;

    @Autowired
    private NodeService nodeService;

    @Override
    public void handle(Map dataMap, EventBus eventBus) {
        //获取聊天历史记录
        ChatHistoryRequest fr = beanMapper.map(dataMap, ChatHistoryRequest.class);
        getHistory(fr, eventBus);
    }


    public void getHistory(ChatHistoryRequest fr, EventBus ebs) {
        if (fr.getLast() == 0) {
            PageHelper.orderBy(" id desc ");
            PageHelper.startPage(1, 100);
            Page<ChatMsg> chatMsgs = this.chatMapper.selectHistory(fr.getSelf(), fr.getReceiver());
            String sendNode = nodeService.getUserNode(fr.getSelf());
            if (!StringUtils.isEmpty(sendNode)) {
                ChatHistroyResponse chatHistroyResponse = new ChatHistroyResponse(chatMsgs);
                ebs.publish(sendNode, ObjectJsonUtil.toString(Response.instance(fr.getSelf(), EnumReturnCode.SUCCESS.getCode(), ObjectJsonUtil.toString(chatHistroyResponse))));
            }
        }
    }


    @Override
    public String getSupport() {
        return "singleHistory";
    }
}

